package SyncMap

import (
	"errors"
	"sync"
)

func GetValue(data *sync.Map, keys ...interface{}) (interface{}, error) {
	self := data

	for i := 0; i < len(keys)-1; i++ {
		key := keys[i].(string)

		child, ok := self.Load(key)
		if !ok {
			return nil, errors.New("找不到指定的目录")
		}

		val, ok := child.(*sync.Map)
		if !ok {
			return nil, errors.New("找不到指定的目录")
		}

		self = val
	}

	key := keys[len(keys)-1]
	val, _ := self.Load(key)

	return val, nil
}

func SetValue(data *sync.Map, keys ...interface{}) {
	self := data

	for i := 0; i < len(keys)-2; i++ {
		key := keys[i].(string)

		child, ok := self.Load(key)
		if !ok {
			self.Store(key, &sync.Map{})
		}
		child, ok = self.Load(key)

		self = child.(*sync.Map)
	}

	key := keys[len(keys)-2]
	val := keys[len(keys)-1]

	self.Store(key, val)
}

func DelValue(data *sync.Map, keys ...interface{}) {
	self := data

	for i := 0; i < len(keys)-1; i++ {
		key := keys[i].(string)

		child, ok := self.Load(key)
		if !ok {
			self.Store(key, &sync.Map{})
		}
		child, ok = self.Load(key)

		self = child.(*sync.Map)
	}

	key := keys[len(keys)-1]

	self.Delete(key)
}
